package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware.ActivitiesDTO;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware.ActivitiesDTO.PrerequisitesDTO;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware.ActivitiesDTO.UploadsDTO;
import com.lance.answer.util.HttpUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>拿到当前学生所有视频课程的链接<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2022/4/19 14:47
 */
public class TestYiWangYiSaveVideoAll2tmppppp {


    public static void main(String[] args) throws Exception {
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


//        String userName = "2251201200582";
//        //  String userName = "2251001204863";
//
//        String pwd = "Ouchn@2021";
    //    String userName = "2144106450255";
     //   String userName = "2235004400984";
    //    String userName = "2251201200582";
        String userName = "2237001202197";
        String pwd = "Ouchn@2021";
        //  String courseId = "14192";
        //   String courseId = "50000001086";
        // String courseId = "50000000896";
        // String courseId = "50000003127";
        //    String courseId = "50000000468";
        //       String courseId = "50000000490";
        //    String courseId = "50000000494";
        //  List<Long> courseIds = Lists.newArrayList(40000000852L);
        // List<Long> courseIds = Lists.newArrayList(40000000852L,40000000840L,40000000860L,40000000861L,40000000863L,40000000871L,40000000885L);
//        List<Long> courseIds = Lists.newArrayList(
//                60000002776L, //城市管理学
//                60000003017L, //当代中国政治制度
//                60000003020L, //公共部门人力资源管理
//                60000002784L, //公共政策概论
//                60000002790L, //计算机应用基础
//                60000002805L, //西方行政学说
//                60000003040L, //政府经济学
//                60000002830l,//"国家开放大学学习指南");
//                60000002836l,//人文英语3
//                60000002851l//形势与政策
//
//
//        );
//        List<Long> courseIds = Lists.newArrayList(
//                14847L,//人力资源管理
//                          14920L,//资源与运营管理
//                14953L,//市场营销学
//                14954L,//管理学基础
//                15062L,// 毛泽东思想和中国特色社会主义理论体系概论
//                16502l,//企业现场管理基础
//                19180l//职业生涯规划（1）
//        );

//        List<Long> courseIds = Lists.newArrayList(
//                70000001280L,//人力资源管理
//                70000001285L,//资源与运营管理
//                70000001489L,//市场营销学
//                70000001509L,//管理学基础
//                70000001573L,// 毛泽东思想和中国特色社会主义理论体系概论
//                70000001577L,//企业现场管理基础
//                70000002165L//职业生涯规划（1）
//        );

        List<Long> courseIds = Lists.newArrayList(
                20000001476L,
                20000001477L,
                20000001486L
        );


        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码
        Thread.sleep(10000);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();

        Thread.sleep(10000);


        for(Long courseId:courseIds){
           try {
               studyVideo(driver,courseId);
           }catch (Exception e){
               e.printStackTrace();
           }
        }




//
    }

    public static void studyVideo(WebDriver driver,Long courseId) throws InterruptedException {
        driver.get("https://lms.ouchn.cn/course/" + courseId + "/ng#/courseware");

        Thread.sleep(5000);
        int page = 1;
        int pageSize = 20;
        boolean hasNextPage = true;
        List<LmsVideoInfo> lmsVideoInfos = Lists.newArrayList();
        while (hasNextPage) {
            Courseware courseware = null;
            try {
                courseware = getUserCourseInfo(driver, courseId, page, pageSize);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.err.println("???11:" + courseware.getActivities().size());
            for (ActivitiesDTO activitiesDTO : courseware.getActivities()) {
                if (null == activitiesDTO) {
                    continue;
                }
                if (null == activitiesDTO.getUploads()) {
                    continue;
                }
                List<PrerequisitesDTO> prerequisites = activitiesDTO.getPrerequisites();
                if (prerequisites != null && prerequisites.size() > 0) {
                    if (prerequisites.get(0).getCompletionCriterion().getHasCompleted()) {
                        /**
                         *   "has_completed": false 这个可以判断  视频作业是否完成，完成就不加入到list集合去了
                         *   这里还需进一步的验证！！！！！！！！
                         */
                        continue;
                    }
                }

                LmsVideoInfo lmsVideoInfo = new LmsVideoInfo();
                lmsVideoInfos.add(lmsVideoInfo);
                lmsVideoInfo.setVideoId(activitiesDTO.getId());

                for (UploadsDTO uploadsDTO : activitiesDTO.getUploads()) {
                    if (null == uploadsDTO.getVideos()||uploadsDTO.getVideos().size()<1) {
                        continue;
                    }
                    //     System.err.println(">>>>>>>>>>>"+uploadsDTO.getVideos().size());
                    lmsVideoInfo.setVideoLength(uploadsDTO.getVideos().get(0).getDuration().intValue());
                }
            }
            if (page >= courseware.getPages()) {
                hasNextPage = false;
            } else {
                //  hasNextPage = false;
                page++;
            }
            Thread.sleep(5000);
        }

        System.err.println("videosDTOSSize:" + lmsVideoInfos.size());

        Collections.sort(lmsVideoInfos);

        for (LmsVideoInfo videoInfo : lmsVideoInfos) {

            System.err.println("id:" + videoInfo.getVideoId());

            try {
                saveVideoInfo(courseId, videoInfo.getVideoId(), videoInfo.getVideoLength(), Util.getCookie(driver.manage().getCookies()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(5000);
        }

        System.err.println("end...............");

    //    Thread.sleep(2000000);
    }

    public static Courseware getUserCourseInfo(WebDriver driver, Long courseId, int page, int pageSize) throws Exception {


        String cookie = Util.getCookie(driver.manage().getCookies());

//        int page = 1;
//        int pageSize=20;
        String getUrl = "https://lms.ouchn.cn/api/course/"+courseId+"/coursewares?conditions=%7B%22category%22:null,%22itemsSortBy%22:%7B%22predicate%22:%22chapter%22,%22reverse%22:false%7D,%22ignore_activity_types%22:%5B%22lesson%22%5D%7D" +
                "&page=" + page + "&page_size=" + pageSize;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        //     heads.put(":path", "/api/course/" + courseId + "/activity-reads-for-user");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        System.err.println("result:::" + result);
        return JSON.parseObject(result, Courseware.class);
    }


    public static void saveVideoInfo(long courseId, long videoId, int videoLength, String cookie) throws Exception {

        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/" + videoId;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen");
        heads.put(":method", "POST");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("origin", "https://lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/activities-read/" + videoId);

        // Map<String,Object> data   = Maps.newHashMap();
        JSONObject saveJson = new JSONObject();
        // 课程ID，固定的
        //   int videoLength = 449;

        // int defaultStep = 60;
      //  int defaultStep = 360 ;
        int defaultStep = 360 ;
        int end = 0;
        while (end < videoLength) {
            saveJson.clear();
            saveJson.put("start", end);
            saveJson.put("end", Math.min((end + defaultStep), videoLength));
            String result = HttpUtil.postJson(postUrl, saveJson, cookie, heads);
            System.err.println(result);
            YiWangYiVideoReturnInfo returnInfo = JSON.parseObject(result, YiWangYiVideoReturnInfo.class);
            /**
             * 4-20 "completeness":"full" 已经为full状态时候，是否可以提前终止while循环？
             * FIXME 需要检查核验
             */
            if("full".equals(returnInfo.getCompleteness())){
                end = videoLength;
                break;
            }
            end = returnInfo.getData().getEnd();
            Thread.sleep(5000);
        }
        saveJson.clear();
        saveJson.put("start", end - 20);
        saveJson.put("end", end);
        System.err.println(HttpUtil.postJson(postUrl, saveJson, cookie, heads));
    }


    /**
     * 将字符串的时间转成秒数
     *
     * @param s 字符串时间 06：03
     * @return 秒数
     */
    public static int getTime(String s) {
        int time = 0;
        try {
            String[] array = s.split(":");
            int i = array.length - 1;
            for (String a : array) {
                time += Math.pow(60, i) * Integer.parseInt(a);
                i--;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }


    //   String js = "document.getElementByClassName(\"mvp-play-progress\").setAttribute(\"style\",\"width: 97.5%;\")";
//        String js = "$('.mvp-play-progress').css('style','width: 20.5%;') ";
//
//        ((JavascriptExecutor) driver).executeScript(js);

    // https://www.cnblogs.com/du-hong/p/15337826.html
//        Thread.sleep(2000);
//        Actions action = new Actions(driver);
//     //   WebElement target = driver.findElement(By.className("mvp-play-progress"));
//      //  WebElement target = findElementByCssSelector(driver,"div[class='mvp-play-progress']",20);
//        WebElement target = findElementByCssSelector(driver,"div[class='mvp-progress-control']",20);
//     //   action.dragAndDropBy(target,1000,0);
//       // action.contextClick(target).moveByOffset(990,0).perform();
//
//     System.err.println("x:"+   target.getLocation().x);
//     System.err.println("y:"+   target.getLocation().y);
//
//     WebElement t1 = driver.findElement(By.cssSelector("button[class='mvp-play-rate-btn']"));
//        System.err.println("t1x:"+   t1.getLocation().x);
//        System.err.println("t1y:"+   t1.getLocation().y);
//
//        action.contextClick(target).moveToElement(t1).perform();
//
//        Thread.sleep(2000000);

}
